import React, { PureComponent, Fragment, Component } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import {
  Row, Col, Card, Form, Input, Radio, Select, Icon, Button, List, Modal, message, DatePicker, TreeSelect, Tag, InputNumber,
} from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import GoodsModal from 'components/Coupon/GoodsModal';
import ChannelModal from 'components/Coupon/ChannelModal';

import TextArea from 'antd/lib/input/TextArea';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
const { Option } = Select;
const { CheckableTag } = Tag;

const formItemLayout1 = {
  labelCol: {
    xs: { span: 14 },
    sm: { span: 2 },
    md: { span: 2 },
    lg: { span: 2 },
  },
  wrapperCol: {
    xs: { span: 8 },
    sm: { span: 8 },
    md: { span: 8 },
    lg: { span: 8 },
  },
};

const formItemLayout = { labelCol: { span: 4 }, wrapperCol: { span: 10 } }

@connect(({ coupon, loading }) => ({
  coupon,
  couponDetail: coupon.couponDetail,
  channelTree: coupon.channelTree,
  goodsList: coupon.goodsList,
  loading: loading.models.coupon,
}))
@Form.create()
export default class ContentAdd extends PureComponent {
  state = {
    channelModalVisible: false,
    goodsModalVisible: false,

    record: null,

    contentIdList: [],

    goodsList: [],

    checkedData: [],

    requireAmt: 0,

  };

  componentDidMount() {
    if (this.props.match.params.couponId != 'new') {
      this.props.dispatch({
        type: 'coupon/fetchCouponDetail',
        payload: { couponId: this.props.match.params.couponId },
        callback: (data) => this._callback(data)
      });
    }

    this.props.dispatch({
      type: 'coupon/fetchChannelTree',
      payload: {},
    });

    this.props.dispatch({
      type: 'coupon/fetchGoodsList',
      payload: {},
    });

  }

  _callback(data) {
    let contentIdList = [];
    if (data && (data.useType == "2") && data.channelList && (data.channelList.length > 0)) {
      for (let i = 0; i < data.channelList.length; i++) {
        contentIdList.push('' + data.channelList[i].channelId)
      }
      this.setState({ record: data, contentIdList: contentIdList })
      this.props.form.setFieldsValue({ contentIdList: contentIdList })
    }
    if (data && data.useType == "1") {
      for (let i = 0; i < data.goodsList.length; i++) {
        contentIdList.push(data.goodsList[i])
      }
      this.setState({ record: data, goodsList: contentIdList })
      this.props.form.setFieldsValue({ contentIdList: contentIdList })
    }else{
      this.setState({ record: data})
    }
    console.log('回填数据----------', data)
  }

  componentWillReceiveProps(nextProps) {
    // console.log('nextPropsnextPropsnextPropsnextProps', nextProps.couponDetail)
    // if (nextProps.couponDetail && (nextProps.couponDetail != this.props.couponDetail)) {
    //   this.setState({ record: nextProps.couponDetail, requireAmt: nextProps.couponDetail.requiredAmt ? (nextProps.couponDetail.requiredAmt > 0) ? 1 : 0 : 0 })
    // }
  }

  _goodsSearch(fieldsValue) {
    console.log(fieldsValue)
    this.props.dispatch({
      type: 'coupon/fetchGoodsList',
      payload: fieldsValue,
    });
  }

  _requiredAmtChange(e) {
    this.setState({
      requireAmt: e.target.value,
    })
  }

  _goodsOk(checkedData) {
    console.log('checkedDatacheckedDatacheckedData', checkedData)
    let newList = []
    for (let i = 0; i < checkedData.length; i++) {
      let one = {}
      one['goodsId'] = checkedData[i].goods_id;
      newList.push(one)
    }

    console.log(newList)

    this.props.form.setFieldsValue({ contentIdList: newList })
    this.setState({
      goodsList: newList
    })
    // if (checkedData && (checkedData.length > 0)) {
    //   for (let i = 0; i < checkedData.length; i++)
    //     this.props.form.setFieldValue({ 'contentIdList': checkedData })
    // }

  }

  _channelOk(checkedChannel) {
    console.log('_channelOk======', checkedChannel)
    this.props.form.setFieldsValue({ contentIdList: checkedChannel })
    this.setState({ contentIdList: checkedChannel })
  }

  changeAmtType = (e) => {
    this.props.form.setFieldsValue({ requiredAmt: 0 })
  }

  _useTypeChange = (e) => {
    // let contentIdList = []
    // if (this.state.record && (this.state.record.useType == "2") && this.state.record.channelList && (this.state.record.channelList.length > 0)) {
    //   for (let i = 0; i < this.state.record.channelList.length; i++) {
    //     contentIdList.push('' + this.state.record.channelList[i].channelId)
    //   }
    // }
    // this.setState({ contentIdList: contentIdList })
    if (e.target.value == "2") {
      this.props.form.setFieldsValue({ contentIdList: this.state.contentIdList })
    }

    if (e.target.value == "1") {
      this.props.form.setFieldsValue({ contentIdList: this.state.goodsList })
    }

  }

  _setChooseModalVisible(type, flag, record) {
    if (type == '1') {
      this.setState({
        goodsModalVisible: flag,
      })
    }
    if (type == '2') {
      this.setState({
        channelModalVisible: flag,
      })
    }
  }

  disabledDate = (current) => {
    // Can not select days before today and today
    return current && current < moment().endOf('day');
  }

  _submit() {
    this.props.form.validateFields((err, fieldsValue) => {
      if (err) return;

      let values = {};
      let newContentList = [];

      if ((fieldsValue.useType != '0') && fieldsValue.contentIdList && (fieldsValue.contentIdList.length > 0)) {
        for (let i = 0; i < fieldsValue.contentIdList.length; i++) {
          console.log(fieldsValue.contentIdList[i])
          let one = {};
          if (this.props.form.getFieldValue('useType') == '1') {
            one['contentId'] = (fieldsValue.contentIdList[i]).goodsId;
          } else {
            one['contentId'] = (fieldsValue.contentIdList[i]);
          }
          newContentList.push(one);
        }
      }

      if (newContentList.length > 0) {
        values = { ...fieldsValue, expireTime: (fieldsValue.expireTime.format('YYYY-MM-DD')), contentIdList: newContentList }
      } else {
        values = { ...fieldsValue, expireTime: (fieldsValue.expireTime.format('YYYY-MM-DD')), }
      }

      delete values.amtType;
      console.log('表单提交数据：：：：？？？', values)

      if (fieldsValue.couponId) {
        this.props.dispatch({
          type: 'coupon/editCoupon',
          payload: values,
          callback: () => { this.props.dispatch(routerRedux.goBack()) }
        });
      } else {
        this.props.dispatch({
          type: 'coupon/addCoupon',
          payload: values,
          callback: () => { this.props.dispatch(routerRedux.goBack()) }
        });
      }


    });
  }

  render() {
    const { form } = this.props;
    const { record } = this.state;
    return (
      <PageHeaderLayout title="">
        <Card>
          <Form>
            {record ?
              <FormItem {...formItemLayout} label="id" style={{ display: 'none' }}>
                {form.getFieldDecorator('couponId', {
                  rules: [{ required: true, message: '请输入名称' }],
                  initialValue: record ? record.couponId : null,
                })(<Input placeholder="请输入名称"/>)}
              </FormItem>
              :
              null
            }

            <FormItem {...formItemLayout} label="名称" >
              {form.getFieldDecorator('couponName', {
                 rules: [{
                  required: true, message: '名称不能为空且不能包含特殊字符',
                  // pattern: /^[^#@！!#%$^&*()_+,.，；‘、?？￥|{}%&*\/|:<>?\"]*$/ 
                  pattern: /^[A-Za-z0-9\u4e00-\u9fa5]*$/
                }],
                initialValue: record ? record.couponName : null,
              })(<Input placeholder="请输入名称"   maxLength={10}/>)}
            </FormItem>

            <FormItem {...formItemLayout} label="关联app">
              {form.getFieldDecorator('appType', {
                rules: [{ required: true, message: '请选择APP类型' }],
                initialValue: record ? ('' + record.appType) : "0",
              })(
                <RadioGroup buttonStyle="solid" >
                  <RadioButton value="0">不限</RadioButton>
                  <RadioButton value="1">小萌早教</RadioButton>
                  <RadioButton value="2">小萌绘本</RadioButton>
                </RadioGroup>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="类型">
              {form.getFieldDecorator('couponType', {
                rules: [{ required: true, message: '请选择类型' }],
                initialValue: record ? ('' + record.couponType) : "0",
              })(
                <RadioGroup buttonStyle="solid" >
                  <RadioButton value="0">抵用券</RadioButton>
                  <RadioButton value="1">折扣券</RadioButton>
                </RadioGroup>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="面额/折扣">
              {form.getFieldDecorator('moneyDiscount', {
                rules: [{ required: true, message: '请输入面额/折扣' }],
                initialValue: record ? record.moneyDiscount : null,
              })(
                form.getFieldValue('couponType') == "0" ?
                  <InputNumber min={0} max={999} step={1} precision={0} placeholder="请输入面额/折扣" style={{ width: '50%' }} />
                  :
                  <InputNumber min={0} max={999} step={1} precision={1} placeholder="请输入面额/折扣" style={{ width: '50%' }} />
              )}
            </FormItem>


            <FormItem {...formItemLayout} label="订单金额">
              {form.getFieldDecorator('amtType', {
                // rules: [{ required: true, message: '请输入订单金额' }],
                initialValue: record ? '' + record.amtType : "0",
              })(
                <RadioGroup onChange={this.changeAmtType}>
                  <Radio value="0">不限</Radio>
                  <Radio value="1">满额</Radio>
                </RadioGroup>
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="满">
              {form.getFieldDecorator('requiredAmt', {
                rules: [{ required: (form.getFieldValue('amtType') == "0" ? false : true), message: '请输入订单金额' }],
                initialValue: record ? record.requiredAmt : 0,
              })(
                <InputNumber min={0} max={999} step={1} precision={1} placeholder="请输入金额" style={{ width: '30%' }} disabled={form.getFieldValue('amtType') == "0" ? true : false} />
              )}
            </FormItem>


            <FormItem {...formItemLayout} label="适用商品">
              {form.getFieldDecorator('useType', {
                rules: [{ required: true, message: '请选择适用商品' }],
                initialValue: record ? ('' + record.useType) : "0",
              })(
                <RadioGroup buttonStyle="solid" onChange={this._useTypeChange}>
                  <RadioButton value="0">不限</RadioButton>
                  <RadioButton value="2">指定频道</RadioButton>
                  <RadioButton value="1">指定商品</RadioButton>
                </RadioGroup>
              )}
            </FormItem>

            {
              form.getFieldValue('useType') == "0" ? null
                :
                <FormItem {...formItemLayout} label="选择频道/商品">
                  {form.getFieldDecorator('contentIdList', {
                    rules: [{ required: true, message: '选择频道/商品' }],
                    initialValue: record ? record.contentIdList : null,
                  })(
                    <span>
                      {
                        this.props.form.getFieldValue('useType') == "2" ?
                          (this.state.contentIdList && (this.state.contentIdList.length > 0)) ?
                            <span>已选{this.state.contentIdList.length}项</span>
                            : null
                          :
                          this.props.form.getFieldValue('useType') == "1" ?
                            (this.state.goodsList && (this.state.goodsList.length > 0)) ?
                              <span>已选{this.state.goodsList.length}项</span>
                              : null
                            : null
                      }
                      <Button style={{ marginLeft: '10px' }}
                        onClick={() => {
                          this._setChooseModalVisible(this.props.form.getFieldValue('useType'), true);
                        }}>
                        选择
                      </Button>
                    </span>
                  )}
                </FormItem>

            }

            <FormItem {...formItemLayout} label="有效期">
              {form.getFieldDecorator('expireTime', {
                rules: [{ required: true, message: '请选择有效期' }],
                initialValue: record ? moment(record.expireTime) : null,
              })(
                <DatePicker disabledDate={this.disabledDate}/>
              )}
            </FormItem>

            <FormItem {...formItemLayout} label="使用说明">
              {form.getFieldDecorator('couponIntr', {
                rules: [{ required: true, message: '请输入使用说明' }],
                initialValue: record ? record.couponIntr : null,
              })(
                <TextArea maxLength="140" />
              )}
            </FormItem>


            <FormItem {...formItemLayout}>
              <Button type="primary" htmlType="submit" onClick={() => this._submit()} style={{ marginLeft: '120px' }} loading={this.props.loading}>
                保存
              </Button>
              <Button type="danger" onClick={() => { this.props.dispatch(routerRedux.goBack()) }} style={{ marginLeft: '15px' }}>
                返回列表
              </Button>
            </FormItem>
          </Form>
        </Card>

        <GoodsModal goodsModalVisible={this.state.goodsModalVisible}
          channelTree={this.props.channelTree}
          goodsList={this.props.goodsList}
          contentIdList={this.state.goodsList}
          setGoodsModalVisible={(type, flag) => this._setChooseModalVisible(type, flag)}
          goodsSearch={(fieldsValue) => this._goodsSearch(fieldsValue)}
          setGoodsCheckedList={(rows) => this._setGoodsCheckedList(rows)}
          goodsOk={(checkedData) => this._goodsOk(checkedData)}
        // goodsCancle= {() => this._closeGoodsModal()}
        />

        <ChannelModal channelModalVisible={this.state.channelModalVisible}
          channelTree={this.props.channelTree}
          contentIdList={this.state.contentIdList}
          setChannelModalVisible={(type, flag) => this._setChooseModalVisible(type, flag)}
          channelOk={(checkedData) => this._channelOk(checkedData)}
        // goodsCancle= {() => this._closeGoodsModal()}
        />

      </PageHeaderLayout>
    )
  }
}